package com.github.wxiaoqi.security.auth.controller;

import com.github.wxiaoqi.security.auth.service.AuthService;
import com.github.wxiaoqi.security.auth.util.user.JwtAuthenticationRequest;
import com.github.wxiaoqi.security.auth.util.user.JwtAuthenticationResponse;
import com.github.wxiaoqi.security.common.admin.pay.response.BaseResponse;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.ResponseCode;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("jwt")
@Slf4j
public class AuthController {
    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @RequestMapping(value = "token", method = RequestMethod.POST)
    public ObjectRestResponse<String> createAuthenticationToken(
            @RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
        log.info(authenticationRequest.getUsername()+" require logging...");
        final String token = authService.login(authenticationRequest);
        return new ObjectRestResponse<>().data(token);
    }

    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public ObjectRestResponse<String> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        return new ObjectRestResponse<>().data(refreshedToken);
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public ObjectRestResponse<?> verify(String token) throws Exception {
        authService.validate(token);
        return new ObjectRestResponse<>();
    }
    /***
     * 根据配置后台配置的platformId 生产token
     * 加密规则:用的sha256;key用的是RSA公私秘钥加密的
     * */
    @RequestMapping(value = "crmToken", method = RequestMethod.POST)
    public JwtAuthenticationResponse createAuthenticationTokenForCrm(@RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
    	String token="";
    	JwtAuthenticationResponse response= new JwtAuthenticationResponse();
    	if(StringUtils.isEmpty(authenticationRequest.getPlatformId())||StringUtils.isEmpty(authenticationRequest.getSaltKey())){
    		log.info("获取授权crmtoken报错：平台编号或盐值不能为空");
    		response.setCode(ResponseCode.INVALID_FIELDS.getCode());
    		response.setMsg((ResponseCode.INVALID_FIELDS.getMessage()));
    		response.setSucess(false);
    		return response;
    	}
    	/**
    	 * 根据platformId获取platformId 对应的公私秘钥，然后用解密获取用户saltkey（签名加密用的盐值）
    	 * */
    	/*ValidateAppInfoRsp appInfoRsp=null;
		try {
			appInfoRsp = authService.getValidateAppInfo(authenticationRequest.getAppId());
			if(null==appInfoRsp||!"200".equals(appInfoRsp.getCode())){
				return ResponseEntity.ok(new JwtAuthenticationResponse(StatesConstants.TOKEN_AUTHCHECKAPPID_CODE.getCode(),StatesConstants.TOKEN_AUTHCHECKAPPID_CODE.getMsg(),""));
			}
		} catch (Exception e2) {
			e2.printStackTrace();
			logger.info("授权验证APPid数据报错:"+e2.getMessage());
			return ResponseEntity.ok(new JwtAuthenticationResponse(StatesConstants.TOKEN_AUTHCHECKAPPID_CODE.getCode(),StatesConstants.TOKEN_AUTHCHECKAPPID_CODE.getMsg(),""));
		}*/
    	/**
    	 * 用应用对应的私钥解密获取签名用的盐值
    	 * */
    	/*byte[]source=Base64Utils.decode(authenticationRequest.getKey());
    	byte[]decryptSaltValue=null;
    	try {
    		decryptSaltValue =RSAUtils.decryptByPrivateKey(source,appInfoRsp.getPrivateKey());
		} catch (Exception e1) {
			logger.info("授权解析传输数据报错:"+e1.getMessage());
			e1.printStackTrace();
			return ResponseEntity.ok(new JwtAuthenticationResponse(StatesConstants.TOKEN_AUTHRESOLVEPARAMS_CODE.getCode(),StatesConstants.TOKEN_AUTHRESOLVEPARAMS_CODE.getMsg(),""));
		}*/
    	/**
    	 * 获取token
    	 * */
    	token = authService.createCrmToken(authenticationRequest.getPlatformId(),authenticationRequest.getSaltKey());
    	response.setSucess(true);
    	response.setToken(token);
        //缓存token
		redisTemplate.opsForValue().set("auth:token_"+authenticationRequest.getPlatformId(),token);
        return response;
        
    }
}